<?php
$cfg_file = "./glog_cfg.ini";
$configs = parse_ini_file($cfg_file);
$dlwz_tb = $configs['dlwz_tb'] . "_" . date("Ymd");
$dlwz_create = sprintf($configs['dlwz_create'], $dlwz_tb);
$error_file = $configs['error_file'];

//$headers = getallheaders();
//$headers = array("cmd"=>"dlwz","game_id"=>"56","area_id"=>0, "group_id"=>1,"mid"=>"56","character_id"=>"character_id","channel_id"=>"channel_id","sub_channel_id"=>"sub_channel_id","platform"=>1,"deviceid"=>"deviceid","itype"=>1);
$headers = $_GET;
$cmd = $headers["cmd"];
$game_id = $headers["game_id"];
$area_id = $headers["area_id"];
$group_id = $headers["group_id"];
$mid = $headers["mid"];
$character_id = $headers["character_id"];
$channel_id = $headers["channel_id"];
$sub_channel_id = $headers["sub_channel_id"];
$platform = $headers["platform"];
$deviceid = $headers["deviceid"];
$itype = $headers["itype"];

function reply2client($status, $info_code, $result = null)
{
	if(!isset($status) || empty($info_code))
	{
		return;
	}
	global $error_file;
	global $headers;
	$reply['status'] = $status;
	$reply['info_code'] = $info_code;
	$reply['time'] = time();

    //print_r($reply);
	//if($result != null)
	//{
		//$reply['result'] = $result;
	//}
    if (isset($error_file) && !empty($error_file))
    {
        $fp = fopen($error_file, "a");
        fwrite($fp,date("Y/m/d H:i:s", time()). " ". json_encode($reply). " client_request:i". $_SERVER['REQUEST_METHOD']. ", client_ip:". $_SERVER['REMOTE_ADDR']. ", http_header:". json_encode($headers). ", result:" . $result . "\n");
        fclose($fp);
    }
	exit(json_encode($reply));
}

function create_handler($conn, $sql_show, $sql_create, $name)
{
	$result = $conn->query($sql_show);
	if($result->num_rows <= 0 || !in_array(array(0=>$name), $result->fetch_all(), true))
	{
		if($conn->query($sql_create))
		{
			return 1;
		}
		else
		{
			//echo $conn->error;
			return 0;
		}
	}
	return 2;
}

if (empty($cmd) || $cmd != "dlwz")
{
    reply2client(0, '10001');
}

$db = new mysqli($configs['host'], $configs['user'], $configs['password'], $configs['database'], $configs['port']);
if ($db->connect_errno)
{
    reply2client(0, '10005', "连接数据库失败 ". $db->connect_error);
}

if(!create_handler($db, "show tables", $dlwz_create, $dlwz_tb))
{
	$db->close();
    reply2client(0, '10006', "创建表失败");
}

$sql_insert = "insert into $dlwz_tb(game_id, area_id, group_id, mid, character_id, channel_id, sub_channel_id, platform, deviceid, itype) values(\"$game_id\", $area_id, $group_id, \"$mid\", \"$character_id\", \"$channel_id\", \"$sub_channel_id\", $platform,  \"$deviceid\", $itype)";
//echo $sql_insert . "\n";
$flag = $db->query($sql_insert);
if (!$flag)
{
    $db->close();
    reply2client(0, '10004', $sql_insert);
}

$db->close();
reply2client(1, '10000');

?>
